package com.major.mytomcat;

import com.major.mytomcat.servlet.IndexServlet;
import com.major.mytomcat.servlet.NotFindServlet;
import com.major.mytomcat.servlet.Servlet;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Properties;
import java.util.UUID;

public class Catalina {

    static {
        try {
            Container.WEB_CONFIG.load(Catalina.class.getClassLoader().getResourceAsStream("web.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        ServerSocket server = new ServerSocket();
        server.bind(new InetSocketAddress(8888));

        while (true) {
            Socket accept = server.accept();

            InputStream inputStream = accept.getInputStream();
            StringBuilder req = new StringBuilder();
            int len;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf)) != -1) {
                req.append(new String(buf, 0, len));
                if (len < 1024) {
                    accept.shutdownInput();
                }
            }

            // 构建请求对象
            Request request = Request.buildRequest(req.toString());
            String url = request.getUrl();

            if ("/favicon.ico".equals(url)) {
                continue;
            }

            Servlet servlet = Container.SERVLET_CONTAINER.get(url);

            if (servlet == null) {
                // 容器里没有
                String fullClassName = Container.WEB_CONFIG.getProperty(url);
                if (!"".equals(fullClassName) && fullClassName != null) {
                    // 创建一个servlet，放在容器里
                    servlet = (Servlet) Class.forName(fullClassName).newInstance();
                } else {
                    servlet = new NotFindServlet();
                }
                Container.SERVLET_CONTAINER.put(url, servlet);
            }

            // 构建响应对象
            Response response = new Response();
            response.setOutput(accept.getOutputStream());

            // 判断有无cookie，或者cookie中有无jsessionid
            if (request.getHeaders().get("cookie") == null || !request.getHeaders().get("cookie").contains("jsessionid")) {
                String jsessionid = UUID.randomUUID().toString();
                Container.SESSIONS.put(jsessionid, new HashMap<>());
                response.addHeader("set-cookie", "jsessionid=" + jsessionid);
            }

            servlet.service(request, response);
        }
    }
}
